<?php

namespace App\Http\Controllers;

use App\Models\User;
use App\Utils\Encrypt;
use Illuminate\Http\Request;
use Laravel\Lumen\Routing\Controller as BaseController;

class Controller extends BaseController
{


    /**
     * @var User|null
     */
    public $loginUser;
    public $loginUserId = 0;

    public function __construct(Request $request)
    {
        $sessionId = $request->cookies->get('session_id');
        if(!$sessionId){
            return;
        }
        $ec = new Encrypt($sessionId);
        $id = $ec->decrypt();
        if(!$id){
            return;
        }
        $this->loginUser = User::whereId($id)->first();
        if($this->loginUser){
            $this->loginUserId = $this->loginUser->id;
        }
    }

    public static function success($data, $code = 0){
        return [
            'code' => $code,
            'err'  => false,
            'msg'  => '',
            'data' => $data,
        ];
    }

    public static function error($msg, $code = 0, $data = null){
        return [
            'code' => $code,
            'err'  => true,
            'msg'  => $msg,
            'data' => $data,
        ];
    }

    public function preview(Request $request){
        $this->validate($request, [
            'data'  => 'required|json',
            'page'  => 'json'
        ]);
        return view('preview', [
            //'auto_sync' => true,
            'page' => json_decode($request->get('page'), true),
            'data' => json_decode($request->get('data'), true)
        ]);
    }
}
